<?php
class PostController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl',
		);
	}

	/**
	 * 访问权限
	 */
	public function accessRules()
	{
		return array(
		    array(
		        'allow',
		        'roles' => array('editor')
		    ),
		    array(
		        'deny',
		        'users' => array('*')
		    )
		);
	}


	public function actionTest()
	{
	    echo 'test';
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * 创建
	 */
	public function actionCreate()
	{
		$model=new Post;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if ($this->getQuery('ct'))
		    $model->clearTempCache();

		$time = null;
		if(isset($_POST['Post'])) {
			$model->attributes=$_POST['Post'];
			if($model->save())
				$this->redirect(array('index', 'cid' => $model->cid));
		} else {
			$time = $model->loadTempCache();
			if ($model->id)
			    $this->redirect(array('notice'));
			if (!empty($time))
			    $time = date('H:i:s', $time);
		}
		$this->render('create',array(
			'model'=>$model,
		    'time' => $time,
		));
	}

	/**
	 * 更新
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		if (!Yii::app()->user->checkAccess('updatePost', $model->uid))
		    throw New CHttpException(403, '没有找到你的笔记！');

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
        $time = '';
		if ($this->getQuery('ct'))
		    $model->clearTempCache();
		elseif ($model->hasTempCache()) {
		    $time = $model->loadTempCache();
		    if ($model->id != $id)
		        $this->redirect(array('notice', 'id' => $id));

		    $time = Yii::app()->format->datetime($time);
		}

		if(isset($_POST['Post'])) {
			$model->attributes=$_POST['Post'];
			if($model->save())
				$this->redirect(array('index', 'cid' => $model->cid));
		}

		$viewData = array(
			'model'=>$model,
		    'time' => $time,
		);
		if (Yii::app()->getRequest()->getIsAjaxRequest()){
		    $this->renderPartial('_form', $viewData);
		} else {
    		$this->render('update',$viewData);
		}
	}

	/**
	 * 删除
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel($id);
			if (!Yii::app()->user->checkAccess('deletePost', $model->uid))
		        throw New CHttpException(403, '没有找到你的笔记！');

			if ($model->uid === Yii::app()->user->id)
			    $model->delete();
			else
			    throw New CHttpException(404);

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_GET['goback']) ? urldecode($_GET['goback']) : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * 首页或列表页
	 */
	public function actionIndex()
	{
		$criteria = new CDbCriteria(array(
		    'select' => 'id, title, add_time, top, publish',
		    'order' => 'top desc, update_time desc',
		    'condition' => 'uid=' . Yii::app()->user->id,
		    'with' => 'category',
		));
		if ($this->getQuery('cid'))
			$criteria->addColumnCondition(array('cid' => $this->getQuery('cid')));
		if ($this->getQuery('tag'))
			$criteria->addSearchCondition('tag', $this->getQuery('tag'));

		$dataProvider=new CActiveDataProvider('Post', array(
			'criteria'=>$criteria,
		    'pagination' => array(
		        'pageSize' => yii::app()->params['postsPerPage'],
		    )
		));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * 管理
	 */
	public function actionAdmin()
	{
		$model=new Post('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Post']))
			$model->attributes=$_GET['Post'];

        if ($this->getQuery('ext')) {
            $this->renderPartial('admin_ext', array(
            	'model'=>$model,
             ));
        } else {
    		$this->render('admin',array(
    			'model'=>$model,
    		));
        }
	}


	/**
	 * save or update post temp cache;
	 */
	public function actionTempcache($id)
	{
		$model=new Post;
		if(isset($_POST['Post'])) {
			$model->attributes=$_POST['Post'];
			$model->id = $id;
			$time = $model->addTempCache();
		}
		$result = array();
		$result['time'] = ($time) ? Date('H:i:s', $time) : '';
		echo json_encode($result);
	}

	public function actionNotice($id = null)
	{
	    $model = new Post();
	    $model->loadTempCache();

	    $this->render('notice', array(
	        'model' => $model,
	        'id' => $id
	    ));
	}

    /**
     * 重建标签
     */
	public function actionRebuildtag()
	{
	    $model = new Post();
	    $model->rebuildTagFrequency();
	    echo 'ok';
	}

	public function actionPublish($id)
	{
	   $option = $this->getQuery('o');
	   if (null !== ($publish = Post::model()->publish($id, $option)))
	       $result = array('publish' => $publish, 'success' => true);
	   else
	       $result = array('success' => false);
	   echo json_encode($result);
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Post::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='post-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
